package com.lottery.im.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lottery.im.BuildConfig;
import com.lottery.im.api.interceptor.Level;
import com.lottery.im.api.interceptor.LoggingInterceptor;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *
 *
 */
public class ApiClient {

  // 默认连接时间（秒）
  private static final int DEFAULT_CONNECT_TIME = 60;

  private static ApiService financeRetrofit;
  protected static final Object monitor = new Object();
  private static OkHttpClient client;
  private static Retrofit retrofit;

  private ApiClient() {
  }

  static {
    Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
        .create();

    client = new OkHttpClient.Builder()
        .connectTimeout(DEFAULT_CONNECT_TIME, TimeUnit.SECONDS)
        .writeTimeout(DEFAULT_CONNECT_TIME, TimeUnit.SECONDS)
        .readTimeout(DEFAULT_CONNECT_TIME, TimeUnit.SECONDS)
        .addInterceptor(new LoggingInterceptor.Builder()
            .loggable(BuildConfig.DEBUG)
            .setLevel(Level.BODY)
            .log(Platform.INFO)
            .build())
        .build();

    retrofit = new Retrofit.Builder()
        .baseUrl(Api.BASEADDRESS)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build();
  }

  public static ApiService getApiRetrofitInstance() {
    synchronized (monitor) {
      if (financeRetrofit == null) {
        financeRetrofit = retrofit.create(ApiService.class);
      }
      return financeRetrofit;
    }
  }
}
